Crate sepserde

source ·
Expand description

§YaSerDe

YaSerDe is a framework for serializing and deserializing Rust data structures efficiently and generically from and into XML.

YaSerDe makes it easy to serialize XML documents given an properly annotated struct. Please refer to the examples directory for the complete code shown below.

§Serialize

For instance, let’s say that one wants to generate a XML file for the Rust-Embedded community. A well known XML file for microcontrollers is called SVD and it can be defined on YaSerDe via structs like so:

 use yaserde_derive::YaSerialize;

 #[derive(Default, PartialEq, Debug, YaSerialize)]
 #[yaserde(rename = "device")]
 struct Device {
   #[yaserde(attribute)]
   schemaversion: String,
   #[yaserde(attribute)]
   xmlns: String,
   #[yaserde(attribute)]
   xsnonamespaceschemalocation: String,
   #[yaserde(child)]
   attributes: DeviceAttributes
 }

 #[derive(Default, PartialEq, Debug, YaSerialize)]
 struct DeviceAttributes {
   #[yaserde(child)]
   vendor: String,
 }

The interspersed #[yaserde()] macros give some indication of what the resulting XML Will look like, namely, a short snippet of the struct above in XML would be depending on concrete values passed to the struct (not shown):

 (...)
 <device schemaversion: "1.0-example", xmlns: "ns:.... example"
 xsnonamespaceschemalocation: "foo_bar_baz">
    <devattributes>
    </devattributes>
 (...)

Notice the important difference in XML output representation between attributes vs child, since SVD expects information in that particular arrangement. YaSerDe allows that serialized XML to be valid unlike other Rust XML (de)serialization crates (i.e quick-xml).

Also the last DevAttrs struct field is indeed another struct, so one can chain several structs to compose the XML structure (again, see examples folder for the complete example).

 [dependencies]
 # serde = { version = "1.0.123", features = [ "derive" ] }
 # quick-xml = { version = "0.21.0", features = [ "serialize" ] }
 yaserde = "0.5.1"
 yaserde_derive = "0.5.1"

Last but not least, in order to have a nice, pretty printed XML output one can do:

    // Display pretty printed XML
   let yaserde_cfg = sepserde::ser::Config{
       perform_indent: true,
       .. Default::default()
   };

    println!("{}", sepserde::ser::to_string_with_config(&dev, &yaserde_cfg).ok().unwrap());

Avoid using either {:?} or {:#?} println! formatters since it’ll garble the output of your XML.

Modules§

  • Generic data structure deserialization framework.
  • Generic data structure serialization framework.

Traits§

  • A visitor that can be implemented to retrieve information from source file.
  • A data structure that can be deserialized from any data format supported by YaSerDe.
  • A data structure that can be serialized into any data format supported by YaSerDe.